<!-- Task Log Modal -->
<div id="taskLogModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeTaskLogModal()">&times;</span>
        <h2>{{_("Task Log")}}</h2>
        <button onclick="refreshTaskLog()">{{_("Refresh Logs")}}</button>
        <div id="taskLogContent"></div>

    </div>
</div>

<script>
    let currentTaskId = null;
    let logInterval = null;

    // Function to open the Task Log modal
    function openTaskLogModal(taskId) {
        currentTaskId = taskId;
        fetchTaskLog();
        document.getElementById("taskLogModal").style.display = "block";
    }

    // Function to close the Task Log modal
    function closeTaskLogModal() {
        if (logInterval) {
            clearInterval(logInterval);
            logInterval = null;
        }
        currentTaskId = null;
        document.getElementById("taskLogModal").style.display = "none";
    }

    // Function to fetch task log
    function fetchTaskLog() {
        if (!currentTaskId) return;
        apiFetch(`background_tasks/task/${currentTaskId}`)
            .then(response => response.json())
            .then(data => {
                const taskLogContent = document.getElementById("taskLogContent");
                taskLogContent.innerHTML = data.status_html.join("<br>");
                // Start interval if task is waiting or running
                if (data.status === "waiting" || data.status === "running") {
                    if (!logInterval) {
                        logInterval = setInterval(fetchTaskLog, 500);
                    }
                } else {
                    if (logInterval) {
                        clearInterval(logInterval);
                        logInterval = null;
                    }
                }
            })
            .catch(error => {
                console.error('Error fetching task log:', error);
            });
    }

    // Function to refresh task log
    function refreshTaskLog() {
        fetchTaskLog();
    }

    // Function to format timestamp to local time string
    function formatTimestamp(timestamp) {
        if (timestamp === -1) return "N/A";
        const date = new Date(timestamp);
        return date.toLocaleString();
    }

</script>